package cn.kgc.shiro;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.Arrays;

/**
 * @author: mosin
 * @version: v1.0  2023/1/9
 * 用户自定义realm
 */
public class CustomerRealm extends AuthorizingRealm {

    // 授权方法    根据用户信息 查询用户拥有的权限 完成授权操作
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        System.out.println(" CustomerRealm doGetAuthorizationInfo ");
        // 获取用户名  username
        String primaryPrincipal = (String) principals.getPrimaryPrincipal();
        // 根据用户身份信息 查询数据库 加载用户拥有权限信息

        // 授权   角色  权限字符串
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        // 角色授权  admin  super
        //simpleAuthorizationInfo.addRole("admin");
        //simpleAuthorizationInfo.addRole("super");

        simpleAuthorizationInfo.addRoles(Arrays.asList("admin","super"));

        // 权限字符串 授权
        //simpleAuthorizationInfo.addStringPermission("user:*");
        //simpleAuthorizationInfo.addStringPermission("user:update");

        simpleAuthorizationInfo.addStringPermissions(Arrays.asList("user:add","user:update"));

        return simpleAuthorizationInfo;
    }


    // 认证方法  编写代码查询数据库
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        System.out.println("------通过自定义realm完成认证------");
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();

        // 根据用户名查询数据库   -> user  username:admin  password:12345  userMapper

        if("admin".equals(username)){
            //SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo("admin", "dc4b56ff4967374b261a29cd4a90580d", this.getName());
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo("admin", "daf143a91c6318a2c637a52824e431ab", ByteSource.Util.bytes("hello"), this.getName());
            return simpleAuthenticationInfo;
        }

        return null;
    }
}
